// Package sys
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2024 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.15.7
package store

import (
	"context"
	"fmt"
	"hotgo/api/api/storeproduct"
	"hotgo/internal/dao"

	"github.com/gogf/gf/v2/util/gconv"
)

var (
	StoreProduct = cStoreProduct{}
)

const UP int = 1
const DOWN int = 2

type cStoreProduct struct{}

// List 查看商品列表
func (c *cStoreProduct) List(ctx context.Context, req *storeproduct.ListReq) (res *storeproduct.ListRes, err error) {
	list := []storeproduct.StoreProduct{}
	totalCount := 0
	err = dao.StoreProduct.Ctx(ctx).Where(dao.StoreProduct.Columns().Status, "1").Page(req.Page, req.PerPage).ScanAndCount(&list, &totalCount, false)
	for i, v := range list {
		list[i] = c.getTextAttribute(v)
	}
	res = new(storeproduct.ListRes)
	res.List = list
	res.PageRes.Pack(req, totalCount)
	return
}

// View 获取指定商品信息
func (c *cStoreProduct) View(ctx context.Context, req *storeproduct.ViewReq) (res *storeproduct.ViewRes, err error) {
	v := storeproduct.StoreProductInfo{}
	err = dao.StoreProduct.Ctx(ctx).WithAll().Where(dao.StoreProduct.Columns().Id, req.Id).Scan(&v)
	if err != nil {
		return
	}
	v.StoreProduct = c.getTextAttribute(v.StoreProduct)
	res = new(storeproduct.ViewRes)
	res.Data = v
	return
}

func (c *cStoreProduct) getTextAttribute(v storeproduct.StoreProduct) storeproduct.StoreProduct {
	if v.Status == UP {
		v.StatusText = "已上架"
	} else {
		v.StatusText = "已下架"
	}
	v.PriceText = fmt.Sprintf("%.2f", gconv.Float32(v.Price/100))
	if v.Stock == 0 {
		v.StockText = "库存不足"
	} else if v.Stock < 10000 {
		v.StockText = fmt.Sprintf("%d", v.Stock)
	} else {
		v.StockText = fmt.Sprintf("%.1f万", gconv.Float32(v.Stock/10000))
	}
	if v.FakeSale < 10000 {
		v.SaleText = fmt.Sprintf("%d", v.FakeSale)
	} else {
		v.SaleText = fmt.Sprintf("%.1f万", gconv.Float32(v.FakeSale/10000))
	}
	return v
}
